﻿#include "VideoRenderViewController.h"


void VideoRenderViewController::Start()
{
	// 创建并启动后台线程
	renderThread = std::make_unique<std::thread>(&VideoRenderViewController::Draw, this);
}
QString VideoRenderViewController::Init()
{
	binaryFileReader = BinaryFileReader::Create();
	iVideoRenderView = IVideoRenderView::Create(IVideoRenderView::SDL);
	if (mWidth <= 0 || mHeight <= 0 || win_id == NULL)
	{
		qDebug() << "请设要播放文件的宽高";
		QString errorMsg = "请设要播放文件的宽高";
		return errorMsg;
	}

	binaryFileReader->filename = mFilePath.toStdString();
	binaryFileReader->width = mWidth;
	binaryFileReader->height = mHeight;
	binaryFileReader->Init();

	IVideoRenderView::PixFormat mFormat = IVideoRenderView::PixFormat::RGBA;
	switch (mPixFormat) {
	case 0:
		mFormat = IVideoRenderView::PixFormat::RGBA;
		data = new  char[mWidth * mHeight * 4];
		linesize = mWidth * mHeight * 4;
		break;
	case 1:
		mFormat = IVideoRenderView::PixFormat::ARGB;
		data = new  char[mWidth * mHeight * 4];
		linesize = mWidth * mHeight * 4;
		break;
	case 2:
		mFormat = IVideoRenderView::PixFormat::RGB24;
		data = new  char[mWidth * mHeight * 3];
		linesize = mWidth * mHeight * 3;
		break;
	case 3:
		mFormat = IVideoRenderView::PixFormat::YUV420P;
		data = new  char[mWidth * mHeight * 1.5];
		linesize = mWidth * mHeight * 1.5;
		break;
	}
	iVideoRenderView->Init(mWidth, mHeight, mFormat, win_id);
	return NULL;
}

/// <summary>
/// 线程函数，执行了线程
/// </summary>
void VideoRenderViewController::Draw()
{
	for (;;)
	{
		if (!isRunning)break;
		bool ret = binaryFileReader->Read(data, linesize);
		if (!ret) {
			break;
		}
		iVideoRenderView->Draw(data);
		int secondMs = (int)(1000 / fps);
		//std::this_thread::sleep_for(33ms);
		std::this_thread::sleep_for(std::chrono::milliseconds(secondMs));
	}
	/*if (data) {
		delete data;
	}*/
	qDebug() << "已释放了data内存";
}
void VideoRenderViewController::Close()
{
	if (!mFilePath.isEmpty()) {
		isRunning = false;
		// 等待线程结束
		if (renderThread && renderThread->joinable()) {
			renderThread->join();
		}
		if (iVideoRenderView) {
			iVideoRenderView->Close();
			iVideoRenderView = NULL;
		}
		binaryFileReader ->Close();

		//iVideoRenderView = NULL;
		isRunning = true;
		//renderThread = nullptr;
		//linesize = 0;
		//mWidth = 0;
		//mHeight = 0;
		//fps = 25;//fps默认25帧每秒
		//mPixFormat = IVideoRenderView::PixFormat::RGBA;
		//win_id = NULL;
		//mFilePath = nullptr;
		if (data) {
			delete data;
			data = NULL;
		}
	}

}

void VideoRenderViewController::Resize(int width, int height)
{
	if (iVideoRenderView) {
		iVideoRenderView->Scale(width, height);
	}
}

